package com.rjpacket.BaiduMapLocated;

import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.*;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.poi.*;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class MainActivity extends Activity implements BDLocationListener, OnGetPoiSearchResultListener, BaiduMap.OnMarkerClickListener, ActionBar.OnNavigationListener, PopupMenu.OnMenuItemClickListener {

    private MapView mapView;
    private BaiduMap map;
    private LocationClient client;
    private Marker myMarker;
    private int index;
    private Overlay currentArea;
    private String keyWord = "美食";
    private EditText editText;
    private PoiSearch poiSearch;
    private List<PoiInfo> data;
    private LatLng latLng;
    private int size;
    private List<Marker> markers;
    private ArrayList<String> data1;

    private ActionBar actionBar;
    private ArrayAdapter<String> adapter;
    private ArrayList<String> city_data;
    private LatLng latLng1;
    private TextView textView;


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        editText = (EditText) findViewById(R.id.et_msg);

        actionBar = getActionBar();

        if(actionBar != null){
            actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
            actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff2228ff")));

            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setDisplayShowTitleEnabled(false);
            actionBar.setDisplayShowCustomEnabled(true);

            actionBar.setCustomView(R.layout.actionbar_title);

            city_data = new ArrayList<String>();
            city_data.add("城市");
            city_data.add("北京");
            city_data.add("安徽");
            city_data.add("上海");
            city_data.add("江苏");
            city_data.add("湖北");

            adapter = new ArrayAdapter<String>(
                    this,
                    android.R.layout.simple_spinner_dropdown_item,
                    city_data
            );
            actionBar.setListNavigationCallbacks(adapter, this);

        }

        mapView = (MapView) findViewById(R.id.bmapView);

        map = mapView.getMap();
        map.setOnMarkerClickListener(this);

        ///////////定位
        LocationClientOption clientOption = new LocationClientOption();
        clientOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        clientOption.setOpenGps(true);
        clientOption.setNeedDeviceDirect(true);
        clientOption.setIsNeedAddress(true);
        clientOption.setAddrType("all");
        clientOption.setCoorType("bd09ll");
        clientOption.setScanSpan(500);
        clientOption.setProdName("BaiduMapLocated");

        Context context = getApplicationContext();
        client = new LocationClient(context,clientOption);
        client.registerLocationListener(this);
        client.start();
        client.requestLocation();

        //poi 检索
        poiSearch = PoiSearch.newInstance();
        poiSearch.setOnGetPoiSearchResultListener(this);

        data = new LinkedList<PoiInfo>();
        markers = new LinkedList<Marker>();


        textView = new TextView(this);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.actionbar_nearby,menu);
        return true;
    }

    public void doMySearch(){
        if(latLng != null) {
            for(Marker m:markers){
                m.remove();
            }
            PoiNearbySearchOption searchOption = new PoiNearbySearchOption();
            searchOption.location(latLng);
            searchOption.keyword(keyWord);
            searchOption.radius(500 + 500 * index);
            searchOption.pageCapacity(40);
            poiSearch.searchNearby(searchOption);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        poiSearch.destroy();
        client.unRegisterLocationListener(this);
        client.stop();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mapView.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mapView.onPause();
    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        int locType = bdLocation.getLocType();
        switch(locType){
            case BDLocation.TypeGpsLocation:
            case BDLocation.TypeCacheLocation:
            case BDLocation.TypeNetWorkLocation:
                if(myMarker != null){
                    myMarker.remove();
                }
                if(currentArea != null){
                    currentArea.remove();
                }
                double latitude = bdLocation.getLatitude();
                double longitude = bdLocation.getLongitude();
                latLng = new LatLng(latitude, longitude);
                //我的图标
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(latLng);
                markerOptions.zIndex(9);
                markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.mylocation));
                myMarker = (Marker) map.addOverlay(markerOptions);
                //我的圆圈
                CircleOptions circleOptions = new CircleOptions();
                circleOptions.fillColor(0xaa00ff00);
                int i = 500 + 500 * index;
                circleOptions.radius(i);
                circleOptions.center(latLng);
                currentArea = map.addOverlay(circleOptions);

                // TODO 移动到中心位置
                MapStatusUpdate statusUpdate = MapStatusUpdateFactory.newLatLng(latLng);
                map.animateMapStatus(statusUpdate);

                doMySearch();
                break;
        }
    }

    public void btnSearch(View view){
        if(view != null){

            keyWord = editText.getText().toString().trim();
            if("".equals(keyWord)){
                keyWord = "美食";
            }
            actionBar.setListNavigationCallbacks(adapter, this);
//            map.clear();
//            myMarker.setVisible(true);
//            currentArea.setVisible(true);
            map.hideInfoWindow();
            client.requestLocation();
            if(latLng1 != null){
                doNearBySearch();
            }else {
                doMySearch();
            }
        }
    }

    @Override
    public void onGetPoiResult(PoiResult poiResult) {
        if(poiResult != null){
            List<PoiInfo> allPoi = poiResult.getAllPoi();
            data.clear();
            if(allPoi != null){
                //得到所有的条目
                size = allPoi.size();
                for (PoiInfo poi : allPoi) {
                    String address = poi.address;
                    String city = poi.city;
                    boolean hasCaterDetails = poi.hasCaterDetails;
                    boolean isPano = poi.isPano;
                    LatLng location = poi.location;
                    String name = poi.name;
                    String phoneNum = poi.phoneNum;
                    String postCode = poi.postCode;
                    PoiInfo.POITYPE type = poi.type;
                    // UID 就代表  POI的ID
                    //那么查询的时候，将uid 提交给查询详情的办法，进行提交获取详情
                    String uid = poi.uid;
                    data.add(poi);

                    //每个点都标记Marker
                    MarkerOptions mark = new MarkerOptions();
                    mark.icon(BitmapDescriptorFactory.fromResource(R.drawable.sign));
                    mark.zIndex(9);
                    mark.position(location);
                    Marker marker = (Marker) map.addOverlay(mark);
                    markers.add(marker);
                }
            }
        }
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
        if(poiDetailResult != null){
            String address = poiDetailResult.getAddress();
            int checkinNum = poiDetailResult.getCheckinNum();
            int commentNum = poiDetailResult.getCommentNum();
            String detailUrl = poiDetailResult.getDetailUrl();
            double environmentRating = poiDetailResult.getEnvironmentRating();
            double facilityRating = poiDetailResult.getFacilityRating();
            LatLng location = poiDetailResult.getLocation();
            String name = poiDetailResult.getName();
            double price = poiDetailResult.getPrice();
            String telephone = poiDetailResult.getTelephone();


            textView.setText(
                    "店名：" + name + "\n" +
                            "地址：" + address + "\n" +
                            "电话：" + telephone + "\n" +
                            "价格：" + price
            );
            textView.setTextColor(Color.RED);
            textView.setBackgroundResource(R.drawable.infowindow);
            textView.setTextSize(10);

            InfoWindow infoWindow = new InfoWindow(textView,location,-76);

            map.showInfoWindow(infoWindow);
        }
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
//        map.hideInfoWindow();
        LatLng position = marker.getPosition();
        PoiInfo poiInfo = null;
        for(PoiInfo p:data){
            if(p.location == position){
                poiInfo = p;
                break;
            }
        }
        if(poiInfo != null) {
            String uid = poiInfo.uid;
            PoiDetailSearchOption poiDetailSearchOption = new PoiDetailSearchOption();
            poiDetailSearchOption.poiUid(uid);
            poiSearch.searchPoiDetail(poiDetailSearchOption);
        }

        return true;
    }

    @Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
        switch(itemPosition){
            case 0:
                latLng1 = null;
                break;
            case 1:
                //北京
                latLng1 = new LatLng(39.915,116.403874);
                break;
            case 2:
                //安徽
                latLng1 = new LatLng(31.836025,117.225782);
                break;
            case 3:
                //上海
                latLng1 = new LatLng(31.239282,121.473526);
                break;
            case 4:
                //江苏
                latLng1 = new LatLng(32.061275,118.790866);
                break;
            case 5:
                //湖北
                latLng1 = new LatLng(30.603467,114.304127);
                break;
        }
        if(latLng1 != null) {
            MapStatusUpdate statusUpdate = MapStatusUpdateFactory.newLatLng(latLng1);
            map.animateMapStatus(statusUpdate);

            //latlng1
            doNearBySearch();
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        switch(itemId){
            case R.id.nearby:
                //切换模式

                PopupMenu popupMenu = new PopupMenu(this,actionBar.getCustomView());
                MenuInflater inflater = popupMenu.getMenuInflater();

                inflater.inflate(R.menu.popupmenu_show, popupMenu.getMenu());

                popupMenu.setOnMenuItemClickListener(this);
                popupMenu.show();
                break;
        }
        return true;
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        int itemId = item.getItemId();
        switch (itemId){
            case R.id.wubai:
                index = 0;

                break;
            case R.id.yiqian:
                index = 1;
                break;
            case R.id.liangqian:
                index = 3;
                break;
        }
        if(latLng1 != null) {
            doNearBySearch();
        }else{
            if(client != null && client.isStarted()) {
                client.requestLocation();
            }
        }
        return true;
    }

    public void doNearBySearch(){
        if(latLng1 != null) {
            for(Marker m:markers){
                m.remove();
            }
            PoiNearbySearchOption searchOption = new PoiNearbySearchOption();
            searchOption.location(latLng1);
            searchOption.keyword(keyWord);
            searchOption.radius(500 + 500 * index);
            searchOption.pageCapacity(40);
            poiSearch.searchNearby(searchOption);
        }
    }
}
